<?php

class TransferController extends AppController {

	var $paginate = array(
		'Transfer' => array('order' => 'Transfer.id DESC', 'limit' => 10)
	);

	public function index() {
		$this->Transfer->recursive = 2;
		$this->set('transfers', $this->paginate());
	}

	public function view($id = null) {
		$this->Transfer->recursive = 2;
		$this->Transfer->id = $id;
		if (!$this->Transfer->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		$transfer = $this->Transfer->read(null, $id);
		$this->set('transfer', $transfer);

		$calculatedShares = unserialize(base64_decode($transfer['Transfer']['calculated_shares']));
		$this->set('commissions', $calculatedShares['mergedCommissions']);
		$this->set('totalCommissioners', $calculatedShares['totalCommissioners']);

	}

	public function add() {
		if ($this->request->is('post')) {
			if (isset($this->request->data['calculate']) && $this->request->data['calculate'] == 1) {
				$commissions = $this->countCommissions();
				$this->request->data['Transfer']['calculated_shares'] = base64_encode(serialize($commissions));
			} else {
				$this->Transfer->create();

				// ak user zmaze commission, posle sa null a to nie je float, takze by to hodilo error
				$this->request->data['Transfer']['commission'] = floatval($this->request->data['Transfer']['commission']);
				if ($this->Transfer->save($this->request->data)) {
					$commissions = $this->countCommissions();
					$this->request->data['Transfer']['calculated_shares'] = base64_encode(serialize($commissions));

					$commissionList = $commissions['commissions'];

					foreach ($commissionList as $type => $commissionTypeList) {
						foreach ($commissionTypeList as $oneCommission) {
							$this->Commission->create();
							$oneCommission['fk_transfer_id'] = $this->Transfer->id;
							$oneCommission['type'] = $type;
							$this->Commission->save($oneCommission);
						}
					}
					// nastavime ponuke status uspesne ukoncene
					$offer = $this->Market->read(NULL, $this->request->data['Transfer']['fk_offer_id']);
					if ($offer) {
						$offer['Market']['status'] = Market::STATUS_FINISHED_SUCCESSFULLY;
						$this->Market->save($offer);
						
						if ($offer['Market']['fk_tipster_id']) {
							$message = '<p>Dobrý deň,</p>';
							$message .= '<p>Váš tip s popisom "' . $offer['Market']['html_description'] . '" v systéme MNH group bol úspešne ukončený.</p>';
							$message .= '<p>Pre viac informacií navštívte systém <a href="http://www.mnh.sk">mnh.sk</a></p>';
							$this->sendMail($offer['Tipster']['email'], 'Úspešný tip', $message);
						}
					}

					// nastavime dopytu status uspesne ukoncene
					$demand = $this->Market->read(NULL, $this->request->data['Transfer']['fk_demand_id']);
					if ($demand) {
						$demand['Market']['status'] = Market::STATUS_FINISHED_SUCCESSFULLY;
						$this->Market->save($demand);
						
						if ($demand['Market']['fk_tipster_id']) {
							$message = '<p>Dobrý deň,</p>';
							$message .= '<p>Váš tip s popisom "' . $demand['Market']['html_description'] . '" v systéme MNH group bol úspešne ukončený.</p>';
							$message .= '<p>Pre viac informacií navštívte systém <a href="http://www.mnh.sk">mnh.sk</a></p>';
							$this->sendMail($demand['Tipster']['email'], 'Úspešný tip', $message);
						}
					}
					
					$this->setFlashSuccess('Záznam bol uložený do databázy.');
					$this->redirect(array('action' => 'index'));
				} else {
					$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
				}
			}
		}
		$this->getOffersAndDemands();
	}

	public function edit($id = null) {
		$this->Transfer->id = $id;
		if (!$this->Transfer->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if (isset($this->request->data['calculate']) && $this->request->data['calculate'] == 1) {
				$commissions = $this->countCommissions();
				$this->request->data['Transfer']['calculated_shares'] = base64_encode(serialize($commissions));
			} else {
				$commissions = $this->countCommissions();
				$this->request->data['Transfer']['calculated_shares'] = base64_encode(serialize($commissions));
				if ($this->Transfer->save($this->request->data)) {

					$commissionList = $commissions['commissions'];

					foreach ($commissionList as $type => $commissionTypeList) {
						foreach ($commissionTypeList as $oneCommission) {
							$commission = $this->Commission->find('first', array('conditions' =>
								array(
									'Commission.fk_transfer_id' => $this->Transfer->id,
									'Commission.fk_person_id' => $oneCommission['fk_person_id'],
									'Commission.type' => $type
								))
							);

							if ($commission) {
								$commission['Commission']['value'] = $oneCommission['value'];
								$this->Commission->save($commission);
							} else {
								$this->Commission->create();
								$oneCommission['fk_transfer_id'] = $this->Transfer->id;
								$oneCommission['type'] = $type;
								$this->Commission->save($oneCommission);
							}
						}
					}
					
					$this->setFlashSuccess('Záznam bol uložený do databázy.');
					$this->redirect(array('action' => 'index'));
				} else {
					$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
				}
			}
		} else {
			$this->request->data = $this->Transfer->read(null, $id);
			$calculatedShares = unserialize(base64_decode($this->request->data['Transfer']['calculated_shares']));
			$this->set('commissions', $calculatedShares['mergedCommissions']);
			$this->set('totalCommissioners', $calculatedShares['totalCommissioners']);
		}
		$this->getOffersAndDemands($id);
	}

	protected function countCommissions() {
		// TODO refactoring, lebo sa v tom nevyzna uz ani diva svina :)
		// TODO ak sa edituje, moze sa menit len suma, takze tu treba nacitat data z parovacej tabulky commission a len zmenit sumu

		$totalTipsters = 0;

		$offerId = intval($this->request->data['Transfer']['fk_offer_id']);
		$offer = $this->Market->find('first', array('conditions' => array('Market.id' => $offerId)));

		if ($offer) {
			$brokerId = intval($offer['Market']['fk_broker_id']);
			if ($brokerId > 0) {
				$broker = $this->Person->find('first', array('conditions' => array('Person.id' => $brokerId)));
				if ($broker) {
					$this->set('broker', $broker);
				}
			}

			$offerTipsterId = intval($offer['Market']['fk_tipster_id']);
			if ($offerTipsterId > 0) {
				$offerTipster = new Person($offerTipsterId);

				if ($offerTipster) {
					$totalTipsters++;

					$offerCommissioners = $offerTipster->getBitches();
					$this->set('offerCommissioners', $offerCommissioners);
				}
			}
		}

		if (isset($this->request->data['Transfer']['fk_demand_id'])) {
			$demandId = intval($this->request->data['Transfer']['fk_demand_id']);
			$demand = $this->Market->find('first', array('conditions' => array('Market.id' => $demandId)));

			$demandTipsterId = intval($demand['Market']['fk_tipster_id']);
			if ($demandTipsterId > 0) {
				$demandTipster = new Person($demandTipsterId);

				if ($demandTipster) {
					$totalTipsters++;

					$demandCommissioners = $demandTipster->getBitches();
					$this->set('demandCommissioners', $demandCommissioners);
				}
			}
		}

		$this->set('totalTipsters', $totalTipsters);

		$commissionValue = floatval($this->request->data['Transfer']['commission']);
		// ak je obchod referencny je to len polovicna suma pre firmu, zvysok ide niekam doprdele ale vraj nas nezaujima kam
		if ($this->request->data['Transfer']['referenced']) {
			$commissionValue = $commissionValue / 2;
		}
		$totalCommissioners = array();		// array with all commissioners first index is person_id second is total_commission_percentage
		
		$totalCommissionPercentageSum = 0;
		
		// vypocet pre maklera
		if (isset($broker) && $broker) {
			if ($totalTipsters == 0) {
				$totalCommission = $broker['PersonType']['commission_0_tipsters'];
			} elseif ($totalTipsters == 1) {
				$totalCommission = $broker['PersonType']['commission_1_tipster'];
			} elseif ($totalTipsters == 2) {
				$totalCommission = $broker['PersonType']['commission_2_tipsters'];
			}

			$totalCommissionPercentageSum += $totalCommission;
			
			$totalCommissionPercentage = isset($totalCommissioners[$broker['Person']['id']]) ?
					$totalCommissioners[$broker['Person']['id']]['total_commission_percentage'] + $totalCommission : $totalCommission;
			$commissioner = array(
				'type' => $broker['PersonType']['title'],
				'name' => $broker['Person']['full_name'],
				'total_commission_percentage' => $totalCommissionPercentage,
				'total_commission_value' => $totalCommissionPercentage * $commissionValue / 100,
			);
			$totalCommissioners[$broker['Person']['id']] = $commissioner;

			$commissioner2 = array(
				'fk_person_type_id' => $broker['PersonType']['id'],
				'fk_person_id' => $broker['Person']['id'],
				'percentage' => $totalCommission,
				'value' => $totalCommission * $commissionValue / 100
			);
			// 1 znamena ze ide o maklera
			$commissions[1][] = $commissioner2;
			$mergedCommissions[1][] = array_merge($commissioner, $commissioner2);
		}

		// vypocet pre ponuku
		if (isset($offerCommissioners) && $offerCommissioners)  {
			foreach ($offerCommissioners as $offerCommissioner) {
				$totalCommission = 0;
				if ($totalTipsters == 1) {
					$totalCommission = $offerCommissioner['Commission']['commission_1_tipster'];
				} elseif ($totalTipsters == 2) {
					$totalCommission = $offerCommissioner['Commission']['commission_2_tipsters'];
				}
				
				$totalCommissionPercentageSum += $totalCommission;

				$totalCommissionPercentage = isset($totalCommissioners[$offerCommissioner['Person']['id']]) ?
						$totalCommissioners[$offerCommissioner['Person']['id']]['total_commission_percentage'] + $totalCommission : $totalCommission;
				$commissioner = array(
					'type' => $offerCommissioner['PersonType']['title'],
					'name' => $offerCommissioner['Person']['full_name'],
					'total_commission_percentage' => $totalCommissionPercentage,
					'total_commission_value' => $totalCommissionPercentage * $commissionValue / 100,
				);
				$totalCommissioners[$offerCommissioner['Person']['id']] = $commissioner;

				$commissioner2 = array(
					'fk_person_type_id' => $offerCommissioner['PersonType']['id'],
					'fk_person_id' => $offerCommissioner['Person']['id'],
					'percentage' => $totalCommission,
					'value' => $totalCommission * $commissionValue / 100
				);
				// 2 znamena ze ide o ponuku
				$commissions[2][] = $commissioner2;
				$mergedCommissions[2][] = array_merge($commissioner, $commissioner2);
			}
		}

		// vypocet pre dopyt
		if (isset($demandCommissioners) && $demandCommissioners) {
			foreach ($demandCommissioners as $demandCommissioner) {
				$totalCommission = 0;
				if ($totalTipsters == 1) {
					$totalCommission = $demandCommissioner['Commission']['commission_1_tipster'];
				} elseif ($totalTipsters == 2) {
					$totalCommission = $demandCommissioner['Commission']['commission_2_tipsters'];
				}
				
				$totalCommissionPercentageSum += $totalCommission;

				$totalCommissionPercentage = isset($totalCommissioners[$demandCommissioner['Person']['id']]) ?
						$totalCommissioners[$demandCommissioner['Person']['id']]['total_commission_percentage'] + $totalCommission : $totalCommission;
				$commissioner = array(
					'type' => $demandCommissioner['PersonType']['title'],
					'name' => $demandCommissioner['Person']['full_name'],
					'total_commission_percentage' => $totalCommissionPercentage,
					'total_commission_value' => $totalCommissionPercentage * $commissionValue / 100,
				);
				$totalCommissioners[$demandCommissioner['Person']['id']] = $commissioner;

				$commissioner2 = array(
					'fk_person_type_id' => $demandCommissioner['PersonType']['id'],
					'fk_person_id' => $demandCommissioner['Person']['id'],
					'percentage' => $totalCommission,
					'value' => $totalCommission * $commissionValue / 100
				);
				// 3 znamena ze ide o dopyt
				$commissions[3][] = $commissioner2;
				$mergedCommissions[3][] = array_merge($commissioner, $commissioner2);
			}
		}

		// vypocet pre firmu
		$company = $this->Person->find('first', array('conditions' => array('Person.id' => Person::PERSON_COMPANY)));
		if ($company) {
			$commissioner = array(
				'type' => $company['PersonType']['title'],
				'name' => $company['Person']['full_name'],
				'total_commission_percentage' => 100 - $totalCommissionPercentageSum,
				'total_commission_value' => (100 - $totalCommissionPercentageSum) * $commissionValue / 100,
			);
			$totalCommissioners[$company['Person']['id']] = $commissioner;

			$commissioner2 = array(
				'fk_person_type_id' => $company['PersonType']['id'],
				'fk_person_id' => $company['Person']['id'],
				'percentage' => 100 - $totalCommissionPercentageSum,
				'value' => (100 - $totalCommissionPercentageSum) * $commissionValue / 100
			);
			// 4 znamena ze ide o firmu
			$commissions[4][] = $commissioner2;
			$mergedCommissions[4][] = array_merge($commissioner, $commissioner2);
		}
		
		$this->set('totalCommissioners', $totalCommissioners);
		$this->set('commissions', $mergedCommissions);
		return array('mergedCommissions' => $mergedCommissions, 'commissions' => $commissions, 'totalCommissioners' => $totalCommissioners);
	}

	protected function getOffersAndDemands($id = NULL) {
		$offers = array();
		$demands = array();

		if ($id !== NULL) {
			$marketIds = array();
			if (isset($this->request->data['Transfer']['fk_offer_id'])) {
				$marketIds[] = $this->request->data['Transfer']['fk_offer_id'];
			}
			if (isset($this->request->data['Transfer']['fk_demand_id'])) {
				$marketIds[] = $this->request->data['Transfer']['fk_demand_id'];
			}
			$marketList = $this->Market->find('all', array('conditions' => array('Market.id' => $marketIds)));
		} else {
			$marketList = $this->Market->find('all', array('conditions' => array('Market.status' => Market::STATUS_IN_PROCESS)));
			$offers[0] = array('commission' => 0, 'title' => 'Vyberte ponuku');
			$demands[0] = 'Vyberte dopyt';
		}
		
		foreach ($marketList as $market) {
			if ($market['Market']['type'] == Market::MT_OFFER) {
				$offer = array(
					'commission' => $market['Market']['commission'],
					'title' => ($market['Market']['fk_client_id'] ? $market['Client']['full_name'] . ' - ' : '') . $market['Market']['description'],
				);
				$offers[$market['Market']['id']] = $offer;
			} elseif ($market['Market']['type'] == Market::MT_DEMAND) {
				$demands[$market['Market']['id']] = ($market['Market']['fk_client_id'] ? $market['Client']['full_name'] . ' - ' : '') . $market['Market']['description'];
			}
		}
		$this->set('offers', $offers);
		$this->set('demands', $demands);
	}


	public function delete($id = null) {
		$this->Transfer->id = $id;
		if (!$this->Transfer->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
		} else {
			if ($this->Transfer->delete()) {
				$this->setFlashSuccess('Záznam bol zmazaný z databázy.');
			} else {
				$errors = array_merge(array('Záznam nebol zmazaný z databázy.'), Errors::getErrors());
				$message = implode("<br />", $errors);
				$this->setFlashError($message);
			}
		}
		$this->redirect(array('action' => 'index'));
	}
}

?>